package com.ncloud.crm.dubboservice.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.dubboservice.SaleDashboardService;
import com.ncloud.crm.mapper.SaleDashboardServiceMapper;

@Service
public class SaleDashboardServiceImpl implements SaleDashboardService {
	private static final Logger logger = LogManager.getLogger(SaleDashboardService.class);
	@Autowired
	public SaleDashboardServiceMapper mapper;
	
	//统计客户数量、本月新增等
	@Override
	public JSONObject getCountSale(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		
		String lyear=LastMonth().get("year");
		String lmonth=LastMonth().get("month");
		String lastTime=lyear+lmonth;
		
		String userId = json.getString("userID");
		JSONObject jsonObject=new JSONObject();
		try{
			//客户数量
			String countCust=mapper.getCountCustByUserId(userId);
			if(countCust == null||countCust == ""){
				countCust = "0";
			}
			jsonObject.put("countCust", countCust);
			//本月新增
			String newCountCust=mapper.getNewCountByUserId(userId);
			if(newCountCust == null||newCountCust == ""){
				newCountCust = "0";
			}
			jsonObject.put("newCountCust",newCountCust);
			//当前销售订单金额总数
			String custOrder=mapper.getSumSaleFee(userId);			
			if(custOrder == null||custOrder == ""){
				custOrder = "0";
			}
			double counts =Double.valueOf( custOrder);
			BigDecimal ss = new BigDecimal(counts/100);  
			double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
			DecimalFormat df = new DecimalFormat("######0.00"); 
			String ff=df.format(f1);
			jsonObject.put("custOrderFee",ff);
			//本月订单收入
			String thisMonthOrder=mapper.getSumSaleThisMonth(userId);
			if(thisMonthOrder == null||thisMonthOrder == ""){
				thisMonthOrder = "0";
			}
			String thisMonthOrder_d=moneyChanges(thisMonthOrder);
			jsonObject.put("thisMonthOrder",thisMonthOrder_d);
			//上月结算金额总数
			String lastMonthOrder=mapper.getSumSaleLastMonth(userId,lastTime);
			if(lastMonthOrder == null||lastMonthOrder == ""){
				lastMonthOrder = "0";
			}
			String lastMonthOrder_d=moneyChanges(lastMonthOrder);
			jsonObject.put("lastMonthOrder",lastMonthOrder_d);			
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonObject;		
	}
	//客户玫瑰图：当前销售客户总的产出金额对比
	@Override
	public JSONArray getCustIndustryFee(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		String userId = json.getString("userID");
		JSONArray jsonArray =new JSONArray();
		List<Map<Object,Object>> listInfo=new ArrayList<Map<Object,Object>>();
		try{
			listInfo=mapper.getCustIndustryFee(userId);	
			for(int i=0;i<listInfo.size();i++){
				Map<Object,Object> map=new HashMap<Object, Object>();
				Map<Object,Object> mapInfo=new HashMap<Object, Object>();
				map=listInfo.get(i);
				
				boolean flag=map.containsKey("industry");
				String industry = null;
				if(flag){
					industry=map.get("industry").toString();
					
					boolean flag1=map.containsKey("fee");
					String fee = null;
					if(flag1){
						fee=map.get("fee").toString();
						}else{
							fee="0";
						}
					String fee_d=moneyChanges(fee);
					mapInfo.put("name",industry);
					mapInfo.put("value",fee_d);
					jsonArray.add(mapInfo);
					}			
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}
	//客户TOP5列表：客户名称、客户所属行业、客户节点数、客户总订单金额
	@Override
	public JSONArray getCustFeeTop5(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		String userId = json.getString("userID");
		JSONArray jsonArray =new JSONArray();
		List<Map<Object,Object>> listInfo=new ArrayList<Map<Object,Object>>();
		try{
			listInfo=mapper.getCustFeeTop5(userId);	
			for(int i=0;i<listInfo.size();i++){
				Map<Object,Object> map=new HashMap<Object, Object>();
				Map<Object,Object> mapInfo=new HashMap<Object, Object>();
				map=listInfo.get(i);
				
				boolean flag=map.containsKey("cust_name");
				String custName = null;
				if(flag){
					custName=map.get("cust_name").toString();
					}
				
				boolean flag1=map.containsKey("industry");
				String industry = null;
				if(flag1){
					industry=map.get("industry").toString();
					}
							
				boolean flag2=map.containsKey("count");
				String count = null;
				if(flag2){
					count=map.get("count").toString();
					}
				boolean flag3=map.containsKey("fee");
				String fee = null;
				String fee_d="0.00";
				if(flag3){
					fee=map.get("fee").toString();
					fee_d=moneyChanges(fee);
					}
				mapInfo.put("custName",custName);
				mapInfo.put("industry",industry);
				mapInfo.put("count",count);
				mapInfo.put("fee",fee_d);
				jsonArray.add(mapInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}
	//当前销售5条最新的订单信息
	@Override
	public JSONArray getNewOrderTop5(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		String userId = json.getString("userID");
		JSONArray jsonArray =new JSONArray();
		List<Map<Object,Object>> listInfo=new ArrayList<Map<Object,Object>>();
		try{
			listInfo=mapper.getNewOrderTop5(userId);	
			for(int i=0;i<listInfo.size();i++){
				Map<Object,Object> map=new HashMap<Object, Object>();
				Map<Object,Object> mapInfo=new HashMap<Object, Object>();
				map=listInfo.get(i);
				//{'订单':'','客户名称':'','订单金额':'','当前状态:''}
				boolean flag=map.containsKey("order_id");
				String orderId = null;
				if(flag){
					orderId=map.get("order_id").toString();
					}
				
				boolean flag1=map.containsKey("cust_name");
				String custName = null;
				if(flag1){
					custName=map.get("cust_name").toString();
					}
							
				boolean flag2=map.containsKey("order_state");
				String orderState = null;
				if(flag2){
					orderState=map.get("order_state").toString();
					}
				boolean flag3=map.containsKey("fee");
				String fee = null;
				String fee_d="0.00";
				if(flag3){
					fee=map.get("fee").toString();
					fee_d=moneyChanges(fee);					
					}
				mapInfo.put("orderId",orderId);
				mapInfo.put("custName",custName);
				mapInfo.put("orderFee",fee_d);
				mapInfo.put("orderState",orderState);
				jsonArray.add(mapInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}

	//获取销售额月统计柱状图
	@Override
	public JSONObject getSaleCountByMonth(JSONObject json){
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		String userId = json.getString("userID");
		JSONObject jsonObject=new JSONObject();
		String year = ThisMonth().get("year");
		
		String taskId = "1007";
		String thisMonth=ThisMonth().get("month");
		List<Map<Object,Object>> countList=new ArrayList<Map<Object,Object>>();
		String thisCountString=null;
		try{
			//销售本月的销售额
			thisCountString=mapper.getSumSaleThisMonth(userId);
			if(thisCountString==null||thisCountString==""){
				thisCountString="0";
			}
			String thisCount_d=moneyChanges(thisCountString);
			countList=mapper.getSaleCountByMonth(taskId, year, userId);
			List<Object> monthList=new ArrayList<Object>();
			for(int i=0;i<12;i++){
				monthList.add(0);
			}
			for(int i=0;i<countList.size();i++){				
				Map<Object,Object> map=new HashMap<Object, Object>();
				map=countList.get(i);
				
				boolean flag=map.containsKey("month");
				String month = null;
				if(flag){
					month=map.get("month").toString();
					}
				
				boolean flag1=map.containsKey("sale_count");
				String saleCount = null;
				String saleCount_d="0.00";
				if(flag1){
					saleCount=map.get("sale_count").toString();
					saleCount_d=moneyChanges(saleCount);
					}
				int monthNum=Integer.parseInt(month);
				//monthList.add(month+"月");
				monthList.set(monthNum-1,saleCount_d);
			}
			int monthN=Integer.parseInt(thisMonth);
			monthList.set(monthN-1,thisCount_d);
			jsonObject.put("data",monthList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonObject;			
	}
	
	public Map<String,String> LastMonth(){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		String time = format.format(cal.getTime());
		String year = time.split("-")[0];
		String day = time.split("-")[1];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",day);
		return dateMap;		
	}
	public Map<String, String> ThisMonth(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String time = sdf.format(date);
		String year = time.split("-")[0];
		String day = time.split("-")[1];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",day);
		return dateMap;		
	}
	//分变元保留两位小数
	public String moneyChanges(String str){
		
		double values = (double)Long.parseLong(str)/100;
		BigDecimal ss = new BigDecimal(values); 
		double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
		DecimalFormat df = new DecimalFormat("######0.00"); 
		String res=df.format(f1);
		return res;
	}			
}
